package com.laomuji.android.mvvm.utils

import android.content.Context
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.view.inputmethod.InputMethodManager

/**
 * 监听输入法是否弹出,弹出/隐藏输入法.
 * @author laomuji666
 * @since 2024/2/21
 */
class SoftKeyBoardUtil {
    companion object{
        fun showKeyboard(view: View) {
            view.requestFocus()
            val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, 0)
        }

        fun hideKeyboard(view: View) {
            val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    interface OnSoftKeyBoardVisibleChangedListener {
        /**
         * 比如底部有个输入数据的View,点击弹出输入法,在某些情况下无法把下面的框弹到输入法的上方
         * 可以在[onShow]时设置marginBottom为[softKeyBoardHeight] - 状态栏高度 - 导航栏高度
         * 状态栏高度和导航栏高度:[ResourceUtil.getStatusBarHeight]和[ResourceUtil.getNavBarHeight]
         */
        fun onShow(softKeyBoardHeight: Int, statusBarHeight: Int, navBarHeight: Int)
        fun onHide()
    }

    private var rootViewVisibleHeight = 0
    private var onGlobalLayoutListener: OnGlobalLayoutListener? = null
    private var isShow = false
    private var softKeyBoardHeight = 0

    fun setOnSoftKeyBoardVisibleChangedListener(
        context: Context,
        listener: OnSoftKeyBoardVisibleChangedListener
    ) {
        val rootView = ViewUtil.unwrapContext(context).window.decorView
        if (onGlobalLayoutListener != null) {
            rootView.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalLayoutListener)
        }
        onGlobalLayoutListener = OnGlobalLayoutListener {

            //获取当前根视图在屏幕上显示的大小
            val rect = Rect()
            rootView.getWindowVisibleDisplayFrame(rect)
            val visibleHeight = rect.height()
            if (rootViewVisibleHeight == 0) {
                rootViewVisibleHeight = visibleHeight
                return@OnGlobalLayoutListener
            }
            //根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变
            if (rootViewVisibleHeight == visibleHeight) {
                return@OnGlobalLayoutListener
            }
            if (rootViewVisibleHeight - visibleHeight > 200) {
                //根视图显示高度变小超过200，可以看作软键盘显示了
                softKeyBoardHeight = rootView.rootView.height - (rect.bottom - rect.top)
                listener.onShow(softKeyBoardHeight, ResourceUtil.getStatusBarHeight(), ResourceUtil.getNavBarHeight())
                rootViewVisibleHeight = visibleHeight
                isShow = true
            } else {
                //根视图显示高度变大超过200，可以看作软键盘隐藏了
                listener.onHide()
                rootViewVisibleHeight = visibleHeight
                isShow = false
            }
        }
        rootView.viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
    }

}